<?php
/*
 * ChangePasswordForm File
 *
 * @link http://riedel-st.de
 * @author Stefan Riedel <sr@riedel-st.de>
 */

/**
 * Our ChangePassword Form Model for Users
 *
 * @author Stefan Riedel
 */
class ChangePasswordForm extends CFormModel {
    public $oldPassword;
    public $newPassword;
    public $newPasswordConfirm;

    public function attributeLabels() {
        return array(
                'oldPassword'=>Yii::t('crm', 'Ihr altes Passwort?'),
                'newPassword'=> Yii::t('crm', 'Neues Passwort'),
                'newPasswordConfirm' => Yii::t('crm', 'Wiederholung neues Passwort'),
        );
    }

    public function rules() {
        return array(
                array('oldPassword, newPassword, newPasswordConfirm', 'required'),
                array('newPassword', 'length', 'min'=>6),
                // password needs to be authenticated
                array('newPasswordConfirm', 'change'),
        );
    }

    /**
     * change the password if old password right
     * and newPassword and newPasswordConfirm are the same
     */
    public function change() {
        $userModel = Users::model();
        $userId = Yii::app()->user->getId();
        $me = $userModel->findByPk($userId);
        if(!$me->checkPassword($this->oldPassword)) {
            $this->addError('oldPassword',Yii::t('crm', 'Das alte Passwort ist leider nicht korrekt!'));
        }
        if($this->newPassword !== $this->newPasswordConfirm) {
            $this->addError('oldPassword',Yii::t('crm', 'Die beiden Passwörter stimmen leider nicht überein!'));
        }
    }
}
?>
